#include "../calypso_api_i.h"

#ifndef CALYPSO_NO_DATETIME

BOOL CalypsoDate14ToTimestamp(DATETIME_ST *dst, WORD src)
{
  if (dst == NULL) return FALSE;
  
  dst->hour   = 0;
  dst->minute = 0;
  dst->second = 0;
  
  /* 01/01/1997 */
  dst->day    = 1;
  dst->month  = 1;
  dst->year   = 1997;
  
  /* increment */
  while (src--)
    datetime_next_day(dst);    
  
  return is_date_valid(dst);
}

WORD CalypsoTimestampToDate14(const DATETIME_ST *src)
{
  DATETIME_ST timestamp;
  register WORD value = 0;
  
  if (src == NULL) goto done;

  memcpy(&timestamp, src, sizeof(DATETIME_ST));
  timestamp.hour   = 0;
  timestamp.minute = 0;
  timestamp.second = 0;

  if (!is_date_valid(&timestamp)) goto done;
  
  if (timestamp.year < 1997) goto done;
  
  while ((timestamp.year  != 1997)
      || (timestamp.month != 1)
      || (timestamp.day   != 1))
  {
    datetime_prev_day(&timestamp);
    value++;
  }
  
done:
  return value;  
}

BOOL CalypsoTime11ToTimestamp(DATETIME_ST *dst, WORD src)
{
  if (dst == NULL) return FALSE;

  dst->hour   = (BYTE) (src / 60);
  dst->minute = (BYTE) (src % 60);
  dst->second = 0;
  
  return TRUE;
}

WORD CalypsoTimestampToTime11(const DATETIME_ST *src)
{
  WORD value = 0;
  
  if (src == NULL) goto done;

  value  = src->hour;
  value *= 60;
  value += src->minute;

done:
  return value;
}

BOOL CalypsoDate14IsBefore(const DATETIME_ST *now, WORD value)
{
  DATETIME_ST chk, _now;

  if (now == NULL)
  {
    get_datetime(&_now);
    now = &_now;
  }
  
  CalypsoDate14ToTimestamp(&chk, value);

#if (SPROX_INS_LIB_TRACE)
  if (trace_level & TRACE_LEVEL_USER_2)   
  {
    trace_s(" end?");
    trace_d(chk.day, 2);
    trace_d(chk.month, 2);
    trace_d(chk.year, 4);
  }
#endif
  
  if (chk.year  > now->year) return TRUE;
  if ((chk.year == now->year) && (chk.month > now->month)) return TRUE;
  if ((chk.year == now->year) && (chk.month == now->month) && (chk.day >= now->day)) return TRUE;

  return FALSE;
}

BOOL CalypsoDate14IsAfter(const DATETIME_ST *now, WORD value)
{
  DATETIME_ST chk, _now;

  if (now == NULL)
  {
    get_datetime(&_now);
    now = &_now;
  }

  CalypsoDate14ToTimestamp(&chk, value);

#if (SPROX_INS_LIB_TRACE)
  if (trace_level & TRACE_LEVEL_USER_2)   
  {
    trace_s(" start?");
    trace_d(chk.day, 2);
    trace_d(chk.month, 2);
    trace_d(chk.year, 4);
  }
#endif
  
  if (chk.year  < now->year) return TRUE;
  if ((chk.year == now->year) && (chk.month < now->month)) return TRUE;
  if ((chk.year == now->year) && (chk.month == now->month) && (chk.day <= now->day)) return TRUE;

  return FALSE;
}

#endif
